package controller

import (
	"gin-service/lib/GinSrv/GinResp"
	"gin-service/lib/GinSrv/GinRouter"
	"gin-service/lib/GormSrv"
	"gin-service/lib/GormSrv/model"
	"github.com/gin-gonic/gin"
)

func DemoController(router GinRouter.Router) {
	router.InitRouter()
	response := new(GinResp.RespImpl)

	router.Get("/select", func(ctx *gin.Context) {
		demoId := ctx.Query("demoId")

		var demoList []model.Demo
		result := GormSrv.GDB().Find(&demoList, demoId)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, demoList)
	})

	router.Get("/query", func(ctx *gin.Context) {
		demoId := ctx.Query("demoId")
		demoName := ctx.Query("demoName")

		db := GormSrv.GDB()
		if demoId != "" {
			db = db.Where("demo_id = ?", demoId)
		}
		if demoName != "" {
			db = db.Where("demo_name != ?", demoName)
		}

		var demoList []model.Demo
		result := db.Find(&demoList)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, demoList)
	})

	router.Post("/post/:id", func(ctx *gin.Context) {
		demoId := ctx.Param("demoId")
		queryStr := ctx.Query("query")

		type Payload struct {
			Name string
			Age int
		}

		payload := Payload{}
		err := ctx.BindJSON(&payload)
		if err != nil {
			panic(err.Error())
		}

		response.DataResp(ctx, gin.H{
			"demoId": demoId,
			"queryStr": queryStr,
			"name": payload.Name,
			"age": payload.Age,
		})
	})

	router.Post("/insert", func(ctx *gin.Context) {
		/*name := ctx.PostForm("name")
		if name == "" {
			panic("name missing")
		}*/

		type Payload struct {
			Name string
		}

		payload := Payload{}
		err := ctx.BindJSON(&payload)
		if err != nil {
			panic(err.Error())
		}

		demo := model.Demo{DemoName: payload.Name}
		result := GormSrv.GDB().Create(&demo)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, demo)
	})

	router.Put("/update", func(ctx *gin.Context) {
		response.DataResp(ctx, gin.H{
			"message": "update",
		})
	})
	
	router.Delete("/delete", func(ctx *gin.Context) {
		response.DataResp(ctx, gin.H{
			"message": "delete",
		})
	})
}
